import React, { useEffect, useState } from "react";
import styles from "./index.less";
import Box from "./components/Box";
import Swiper from "./components/Box";
import BoxDrag from "./components/BoxDrag";
import BoxDrop from "./components/BoxDrop";
import DragPreview from "./components/DragPreview";
import { uuid } from "./util";
const components = { Box: Box, Swiper: Swiper };
const componentList = [
  {
    id: uuid(),
    type: "BOX",
    name: "red",
    bgColor: "red",
    h: 100,
    w: 100,
  },
  { id: uuid(), type: "BOX", name: "blue", bgColor: "blue", h: 100, w: 100 },
  {
    id: uuid(),
    type: "Swiper",
    name: "yellow",
    bgColor: "yellow",
    h: 100,
    w: 100,
  },
  {
    id: uuid(),
    type: "BOX",
    name: "c989e2",
    bgColor: "#c989e2",
    h: 100,
    w: 100,
  },
  {
    id: uuid(),
    type: "BOX",
    name: "2bc755",
    bgColor: "#2bc755",
    h: 100,
    w: 100,
  },
  {
    id: uuid(),
    type: "BOX",
    name: "aec72b",
    bgColor: "#aec72b",
    h: 100,
    w: 100,
  },
];

function CanvasView() {
  const [list, setList] = useState([]);
  const [_toId, setToId] = useState("");
  const onAdd = (item) => {
    item.id = uuid();
    list.push(item);
   setList([...list]);
  };

  const onRemove = (item) => {
    const index = list.findIndex((sitem) => sitem.id === item.id);
    list.splice(index, 1);
    setList([...list]);
  };

  const onDrop = (id) => {
    setToId(id);
  };

  const onSwap = ({ formId, toId }) => {
    let fromIndex = -1;
    let toIndex = -1;

    list.forEach((item, index) => {
      if (formId && item.id === formId) {
        fromIndex = index;
      }
      if (toId && item.id === toId) {
        toIndex = index;
      }
    });
    list.splice(toIndex, 0, list.splice(fromIndex, 1)[0]);
    setList([...list]);
  };
  useEffect(() => {
    console.log("======>",111)
     window.parent.postMessage({ list, type: 5 }, "*"); 
  })

  return (
    <div className={styles.canvasView}>dasdsadas
      <div className={styles.left}>
        {componentList.map((item, index) => {
          return (
            <BoxDrag
              onSwap={onAdd}
              toId={_toId}
              item={item}
              type="BOX"
              key={item?.id}
            />
          );
        })}
      </div>
      <div className={styles.center}>
        <DragPreview accept="BOX" onDrop={onDrop}>
          {list.map((item, index) => {
            return (
              <BoxDrop
                key={item.key}
                onRemove={() => onRemove(item, index)}
                isShow={true}
                item={item}
                toId={_toId}
                onSwap={onSwap}
              >
                <Box item={item} />
              </BoxDrop>
            );
          })}
        </DragPreview>
      </div>
      <div className={styles.right}></div>
    </div>
  );
}

export default CanvasView;
